package cn.itcast.flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author lilulu
 * @date 2023-03-29 0:27
 */
public class WordCount {
    public static void main(String[] args) throws Exception {
        /**
         * 使用Flink计算引擎实现实时流计算：词频统计WordCount，从TCP Socket消费数据，结果打印控制台。
         * 1.执行环境-env
         * 2.数据源-source
         * 3.数据转换-transformation
         * 4.数据接收器-sink
         * 5.触发执行-execute
         */
        ParameterTool parameterTool = ParameterTool.fromArgs(args);
        if (parameterTool.getNumberOfParameters() != 2) {
            System.out.println("Usage: WordCount --host <hostname> --port <port> .........");
            System.exit(-1);
        }
        String host = parameterTool.get("host");
        int port = parameterTool.getInt("port", 9999);

        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> source = executionEnvironment.socketTextStream(host, port);
        SingleOutputStreamOperator<Tuple2<String, Integer>> resultData = source.flatMap(
                new FlatMapFunction<String, String>() {
                    public void flatMap(String lines, Collector<String> collector) throws Exception {
                        String[] words = lines.trim().split("\\s+");
                        for (String word : words) {
                            collector.collect(word);
                        }
                    }
                }
        ).map(
                new MapFunction<String, Tuple2<String, Integer>>() {
                    public Tuple2<String, Integer> map(String word) throws Exception {
                        return Tuple2.of(word, 1);
                    }
                }
        ).keyBy(0).sum(1);

        resultData.print();
        executionEnvironment.execute();
    }
}
